package com.shijunhao.graduation.handler.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.shijunhao.graduation.domain.entity.OrgUser;
import com.shijunhao.graduation.service.business.IBusinessUserInfoService;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author: shijunhao
 * @date: 2022/3/4 16:59
 * @description: mybatis plus 自动更新插入填充数据
 */
@Component
public class AutoFillHandler implements MetaObjectHandler {

    private final IBusinessUserInfoService businessUserInfoService;

    @Autowired
    public AutoFillHandler(IBusinessUserInfoService businessUserInfoService) {
        this.businessUserInfoService = businessUserInfoService;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter("createBy") && metaObject.hasGetter("createDate")
                && metaObject.hasGetter("updateBy") && metaObject.hasGetter("updateDate")
                && metaObject.hasGetter("deleted")) {
            OrgUser user = businessUserInfoService.getCurrentUser();
            Date now = new Date();
            setFieldValByName("createDate", now, metaObject);
            setFieldValByName("updateDate", now, metaObject);
            setFieldValByName("deleted", false, metaObject);
            if(user != null){
                Long uid = user.getId();
                setFieldValByName("createBy", uid, metaObject);
                setFieldValByName("updateBy", uid, metaObject);
            }

        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter("updateBy") && metaObject.hasGetter("updateDate")) {
            OrgUser user = businessUserInfoService.getCurrentUser();
            setFieldValByName("updateDate", new Date(), metaObject);
            if(user != null){
                setFieldValByName("updateBy", user.getId(), metaObject);
            }
        }
    }
}
